package com.zhiche.wms.service.base.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.enums.TableStatusEnum;
import com.zhiche.wms.domain.mapper.base.StoreAreaMapper;
import com.zhiche.wms.domain.mapper.base.StoreLocationMapper;
import com.zhiche.wms.domain.mapper.stock.StockMapper;
import com.zhiche.wms.domain.model.base.StoreArea;
import com.zhiche.wms.domain.model.base.StoreLocation;
import com.zhiche.wms.domain.model.base.ValidArea;
import com.zhiche.wms.domain.model.stock.Stock;
import com.zhiche.wms.service.base.IStoreAreaService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zhiche.wms.service.utils.CommonFields;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 库区配置 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-06-08
 */
@Service
public class StoreAreaServiceImpl extends ServiceImpl<StoreAreaMapper, StoreArea> implements IStoreAreaService {

    @Autowired
    private StoreLocationMapper storeLocationMapper;
    @Autowired
    private StockMapper stockMapper;

    @Override
    public Page<StoreArea> queryByPage(Page<StoreArea> page) {
        if (Objects.isNull(page) || Objects.isNull(page.getCondition())) {
            throw new BaseException("参数不能为空");
        }
        List<StoreArea> areaList = null;
        Wrapper<StoreArea> ew = buildCondition(page.getCondition());
        areaList = this.baseMapper.queryByPage(page, ew);
        page.setRecords(areaList);
        return page;
    }

    @Override
    public int getCountByCodeName(StoreArea storeArea) {
        if (Objects.isNull(storeArea) || Objects.isNull(storeArea)) {
            throw new BaseException("参数不能为空");
        }
        if (storeArea.getStoreHouseId() == null || StringUtils.isBlank(storeArea.getStoreHouseId().toString())) {
            throw new BaseException("仓库id不能为空");
        }
        if (StringUtils.isBlank(storeArea.getCode())) {
            throw new BaseException("库区编码不能为空");
        }
        if (StringUtils.isBlank(storeArea.getName())) {
            throw new BaseException("库区名称不能为空");
        }
        Wrapper<StoreArea> ew = new EntityWrapper<>();
        ew.eq("store_house_id", storeArea.getStoreHouseId().toString());
        ew.andNew().eq("code", storeArea.getCode()).or().eq("name", storeArea.getName());
        int count = this.baseMapper.getCountByCode(ew);
        return count;
    }

    @Override
    public boolean updateStoreArea(StoreArea storeArea) {
        Wrapper<StoreArea> ew = new EntityWrapper<>();
        ew.eq("name",storeArea.getName()).eq("store_house_id",storeArea.getStoreHouseId())
                .ne("id",storeArea.getId());
        int selectCount = selectCount(ew);
        if (selectCount > 0){
            throw new BaseException("库区名称已存在");
        }
        boolean updateById = updateById(storeArea);
        return updateById;
    }

    @Override
    public void batchUpdateStatus (Map<String, String> params) {
        this.checkBatchUpdateStatusParam(params);

        if (!StringUtils.isEmpty(params.get("handleType"))) {
            //查询是否有可用库区/库位
            if (params.get("handleType").equals(TableStatusEnum.STATUS_0.getCode())) {
                this.usefulAreaLocation(params);
            }
            String[] keyIds = params.get("keys").split(",");
            if ("area".equals(params.get("type"))) {
                EntityWrapper<StoreArea> areaEw = new EntityWrapper<>();
                areaEw.in("id", Arrays.asList(keyIds));
                StoreArea storeArea = new StoreArea();
                storeArea.setStatus(TableStatusEnum.STATUS_20.getCode());
                if (params.get("handleType").equals(TableStatusEnum.STATUS_1.getCode())) {
                    storeArea.setStatus(TableStatusEnum.STATUS_10.getCode());
                }
                baseMapper.update(storeArea, areaEw);
            } else if ("location".equals(params.get("type"))) {
                EntityWrapper<StoreLocation> locationEw = new EntityWrapper<>();
                locationEw.in("id", Arrays.asList(keyIds));
                StoreLocation storeLocation = new StoreLocation();
                if (params.get("handleType").equals(TableStatusEnum.STATUS_0.getCode())) {
                    storeLocation.setStatus(TableStatusEnum.STATUS_20.getCode());
                }
                if (params.get("handleType").equals(TableStatusEnum.STATUS_1.getCode())) {
                    storeLocation.setStatus(TableStatusEnum.STATUS_10.getCode());
                }
                storeLocationMapper.update(storeLocation, locationEw);
            }
        }
        // 增加批量更改库位类型属性,10,20,30,40,50 hgy 20200805
        if (!StringUtils.isEmpty(params.get("locationType"))) {
            String[] keyIds = params.get("keys").split(",");
            if ("location".equals(params.get("type"))) {
                EntityWrapper<StoreLocation> locationEw = new EntityWrapper<>();
                locationEw.in("id", Arrays.asList(keyIds));
                StoreLocation storeLocation = new StoreLocation();
                if (params.get("locationType").equals(TableStatusEnum.STATUS_10.getCode())) {
                    storeLocation.setType(TableStatusEnum.STATUS_10.getCode());
                }
                if (params.get("locationType").equals(TableStatusEnum.STATUS_20.getCode())) {
                    storeLocation.setType(TableStatusEnum.STATUS_20.getCode());
                }
                if (params.get("locationType").equals(TableStatusEnum.STATUS_30.getCode())) {
                    storeLocation.setType(TableStatusEnum.STATUS_30.getCode());
                }
                if (params.get("locationType").equals(TableStatusEnum.STATUS_40.getCode())) {
                    storeLocation.setType(TableStatusEnum.STATUS_40.getCode());
                }
                if (params.get("locationType").equals(TableStatusEnum.STATUS_50.getCode())) {
                    storeLocation.setType(TableStatusEnum.STATUS_50.getCode());
                }
                storeLocationMapper.update(storeLocation, locationEw);
            }
        }
    }

    @Override
    public List<ValidArea> queryValidArea (String storeHouseId) {
        return baseMapper.queryValidArea(storeHouseId);
    }

    @Override
    public List<ValidArea> queryWDValidArea (Long storeHouseId) {
        if(null == storeHouseId){
            throw new BaseException("仓库id不能为空");
        }
        return baseMapper.queryWDValidArea(storeHouseId);
    }

    @Override
    public List<StoreArea> queryMovementArea (Map<String, String> param) {
        if (null == param || param.isEmpty()) {
            throw new BaseException("参数不能为空");
        }
        if (StringUtils.isBlank(param.get("storeHouseId"))) {
            throw new BaseException("仓库id不能为空");
        }
        EntityWrapper<StoreArea> areaEw = new EntityWrapper<>();
        areaEw.eq("type", TableStatusEnum.STATUS_40.getCode());
        areaEw.eq(CommonFields.STORE_HOUSE_ID.getCode(), param.get("storeHouseId"));
        List<StoreArea> storeAreas = baseMapper.selectList(areaEw);
        if(CollectionUtils.isEmpty(storeAreas)){
            throw new BaseException("当前仓库没有无单区的库区可选择,请新增无单库区");
        }
        return storeAreas;
    }

    /**
     * 查询是否有可用的库区库位
     */
    private void usefulAreaLocation (Map<String, String> params) {
        if ("area".equals(params.get("type"))) {
         EntityWrapper<StoreLocation> locationEw = new EntityWrapper<>();
         locationEw.in("store_area_id",params.get("keys"));
         List<StoreLocation> storeLocations = storeLocationMapper.selectList(locationEw);
         if(CollectionUtils.isNotEmpty(storeLocations)){
             StringBuffer locationIds = new StringBuffer();
             for(StoreLocation storeLocation:storeLocations){
                 locationIds.append(storeLocation.getId()).append(",");
             }
             if(StringUtils.isNotEmpty(locationIds)){
                 this.userfulLocation(locationIds.toString());
             }
         }
        } else if ("location".equals(params.get("type"))) {
            this.userfulLocation(params.get("keys"));
        }
    }

    private void userfulLocation (String keys) {
        StringBuffer sb = new StringBuffer();
        EntityWrapper<Stock> stockEw = new EntityWrapper<>();
        stockEw.in("location_id", Arrays.asList(keys));
        stockEw.gt("qty",0);
        List<Stock> stocks = stockMapper.selectList(stockEw);
       if(CollectionUtils.isNotEmpty(stocks)){
           throw new BaseException("有可用库位正在使用中，不能被禁用！");
       }
    }

    /**
     * 参数校验
     */
    private void checkBatchUpdateStatusParam (Map<String, String> params) {
        if (null == params || params.isEmpty()) {
            throw new BaseException("请传递批量禁用的参数！");
        }
        if (Objects.isNull(params) || StringUtils.isEmpty(params.get("keys"))) {
            throw new BaseException("请传递【keys】批量禁用的参数！");
        }
        if (Objects.isNull(params) || StringUtils.isEmpty(params.get("type"))) {
            throw new BaseException("请传递【type】批量禁用的类型！");
        }
        if (Objects.isNull(params) || StringUtils.isEmpty(params.get("handleType"))) {
            if (Objects.isNull(params) || StringUtils.isEmpty(params.get("locationType"))) {
                throw new BaseException("请传递【handleType】或【locationType】操作方式！");
            }
        }
        if (Objects.isNull(params) || StringUtils.isEmpty(params.get("locationType"))) {
            if (Objects.isNull(params) || StringUtils.isEmpty(params.get("handleType"))) {
                throw new BaseException("请传递【handleType】或【locationType】操作方式！");
            }
        }
    }

    private Wrapper<StoreArea> buildCondition(Map<String, Object> condition) {
        Wrapper<StoreArea> ew = new EntityWrapper<>();
        if (condition.containsKey("houseId") && Objects.nonNull(condition.get("houseId"))) {
            ew.eq("store_house_id", condition.get("houseId").toString());
        }
        if (condition.containsKey("name") && Objects.nonNull(condition.get("name"))) {
            ew.like("name", condition.get("name").toString());
        }
        if (condition.containsKey("type") && Objects.nonNull(condition.get("type"))) {
            ew.eq("type", condition.get("type").toString());
        }
        if (condition.containsKey("status") && Objects.nonNull(condition.get("status"))) {
            ew.eq("status", condition.get("status").toString());
        }
        ew.orderBy("id");
        return ew;
    }

}
